<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $order = $this->request->get("order", "DESC");
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
            $where = [];
            $uid = $this->request->request('uid');
            if ($uid) {
                $where['fromid'] = $uid;
            }
            $total = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => &$v) {
                $v->hidden(['password', 'salt']);
                $v['money'] = $v['money'] ? $v['money'] : 0;
                $v['fromname'] = Db('user')->where('id', $v['fromid'])->value('username');
                $v['frommobile'] = Db('user')->where('id', $v['fromid'])->value('mobile');
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 操作
     */
    public function operate($ids = NULL)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $id = $this->request->post('id');
            $do = $this->request->post('do');
            switch ($do) {
                case 'incMoney'://充值
                    $this->incMoney($id, $params);
                    break;
                case 'buyCard'://办卡
                    $this->buyCard($id, $params);
                    break;
                case 'tijian'://体检
                    $this->gHTJ($id, $params);
                    break;
                case 'guahao'://挂号
                    $this->gHTJ($id, $params);
                    break;
            }
        } else {
            $ids = $ids ? $ids : $this->request->request('ids');
            $row = Db('user')->where('id', $ids)->find();
            if (!$row)
                $this->error(__('No Results were found'));
            $row['fromid'] = $row['fromid'] ? Db('user')->where('id', $row['fromid'])->value('username') : '';
            //获取优惠券列表
            $ticket = Db('user_ticket')->where(['uid' => $ids, 'status' => 0])->field("id,money,get_time,name")->select();
            $radioHtml = "";
            $checkBox = "";
            if ($ticket) {
                foreach ($ticket as $t) {
                    $getTime = date('Y-m-d', $t['get_time']);
                    $radioHtml .= "<tr>
                        <th><input  name=\"row[ticket]\"  type=\"radio\" 
                                   value=\"{$t['id']}\" data-money='{$t['money']}'></th>
                        <th>{$t['name']}</th>
                        <th>{$t['money']}</th>
                        <th>{$getTime}</th>
                    </tr>";
                    $checkBox .= "<tr>
                        <th><input  name=\"row[ticket][]\"  type=\"checkbox\"  onclick='checkOption(this)'
                                   value=\"{$t['id']}\" data-money='{$t['money']}'></th>
                        <th>{$t['name']}</th>
                        <th>{$t['money']}</th>
                        <th>{$getTime}</th>
                    </tr>";
                }
            }
            $row['ticket_radio'] = $radioHtml;
            $row['ticket_checkbox'] = $checkBox;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

    }

    /**
     * 办卡
     */
    public function buyCard($id, $params)
    {

        if (empty($params))
            $this->error('请输入卡号');
        Db()->startTrans();
        $User = Db('user')->where('id', $id)->find();
        $fromId=$User['fromid']?$User['fromid']:0;
        //修改用户金额
        try {
            $userFromeRe = Db('user')->where(['id' => $fromId])->setInc('money', 3);
            $userRe = Db('user')->where('id', $id)->update(['cardno' => $params['cardno']]);

            //添加优惠劵
            $userTicket = Db('user_ticket')->insert([
                'uid' => $fromId, 'get_time' => time(), 'name' => '推广奖励', 'type' => 1, 'money' => 3
            ]);
            //添加消费记录
            $logRe = Db('bonus_log')->insert([
                'uid' => $fromId, 'get_time' => time(), 'message' => '推广奖励', 'type' => 2, 'bonus' => 3
            ]);
            if ( $userTicket && $userRe&&$logRe) {
                Db()->commit();
                $this->success();
            } else {
                Db()->rollback();
                $this->error('充值失败');
            }
        } catch (Exception $e) {
            Db()->rollback();
            $this->error($e);
        }
    }

    /**
     * 充值
     */
    public function incMoney($id, $params)
    {
        if (empty($params))
            $this->error('请输入充值金额');
        Db()->startTrans();
        //修改用户金额
        try {
            $userRe = Db('user')->where('id', $id)->setInc('money', $params['money']);
            //添加优惠劵
            $userTicket = Db('user_ticket')->insert([
                'uid' => $id, 'get_time' => time(), 'name' => '系统发放', 'type' => 2, 'money' => $params['money']
            ]);
            //添加消费记录
            $logRe = Db('bonus_log')->insert([
                'uid' => $id, 'get_time' => time(), 'message' => '系统发放', 'type' => 1, 'bonus' => $params['money']
            ]);
            if ($userRe && $userTicket&&$logRe) {
                Db()->commit();
                $this->success();
            } else {
                Db()->rollback();
                $this->error('充值失败');
            }
        } catch (Exception $e) {
            Db()->rollback();
            $this->error($e);
        }
    }

    /**
     * 挂号/体检
     */
    public function gHTJ($id, $params)
    {
        if (empty($params)||$params['total']==0)
            $this->error('请选择优惠券');
        Db()->startTrans();
        //修改用户金额
        try {
            //使用优惠劵
            if (is_array($params['ticket'])) {
                //体检
                $total = $params['total'];
                $userRe = Db('user')->where('id', $id)->setDec('money', $total);
                foreach ($params['ticket'] as $vt) {
                    $userTicket = Db('user_ticket')->where('id', $vt)->update(['status' => 1]);
                }
                //添加消费记录
                $logRe = Db('bonus_log')->insert([
                    'uid' => $id, 'get_time' => time(), 'message' => '体检消费', 'type' => 3, 'bonus' => -$total
                ]);
                //添加订单
                $OrderRe = Db('order')->insert([
                    'uid' => $id, 'ordertime' => time(), 'ordername' => '体检消费', 'ordertype' => 2, 'orderprice' => $total
                ]);
            } else {
                //挂号
                $userTicket = Db('user_ticket')->where('id', $params['ticket'])->update(['status' => 1]);
                $total=Db('user_ticket')->where('id', $params['ticket'])->value('money');
                $userRe = Db('user')->where('id', $id)->setDec('money', $total);
                //添加消费记录
                $logRe = Db('bonus_log')->insert([
                    'uid' => $id, 'get_time' => time(), 'message' => '挂号消费', 'type' => 4, 'bonus' => -3
                ]);
                //添加订单
                $OrderRe = Db('order')->insert([
                    'uid' => $id, 'ordertime' => time(), 'ordername' => '挂号消费', 'ordertype' => 1, 'orderprice' => 3
                ]);
            }
            if ($userRe && $userTicket&&$logRe&&$OrderRe) {
                Db()->commit();
                $this->success();
            } else {
                Db()->rollback();
                $this->error('充值失败');
            }
        } catch (Exception $e) {
            Db()->rollback();
            $this->error($e);die;
        }
    }
}
